﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Aliyun.MNS;
using Aliyun.MNS.Model;

namespace Framework.MQS
{
    public class AliyunQueue : IQueue
    {
        private const string _accessKeyId = "c0j2z6IGYrDP7jVe";
        private const string _secretAccessKey = "K6QRsaqEOq7dTQup5nmugI4QJRWqwO";
        private const string _endpoint = "http://1307221029824444.mns.cn-qingdao.aliyuncs.com";
        private readonly IMNS _client;
        private const string _queueName = "logQueue";
        public AliyunQueue()
        {
            _client = new MNSClient(_accessKeyId, _secretAccessKey, _endpoint);
        }
        /// <summary>
        /// 队列中是否有数据
        /// </summary>
        public bool IsData
        {
            get
            {
                var nativeQueue = _client.GetNativeQueue(_queueName);
                try
                {
                    nativeQueue.PeekMessage();
                    return true;
                }
                catch
                {
                    return false;
                }
            }
            private set { }
        }
        public void Pop(Func<string, bool> func)
        {
            try
            {
                var nativeQueue = _client.GetNativeQueue(_queueName);
                var receiveMessageResponse = nativeQueue.ReceiveMessage();
                var mes = receiveMessageResponse.Message;
                //处理完成返回True时才执行删除
                if (func(mes.Body))
                {
                    nativeQueue.DeleteMessage(mes.ReceiptHandle);
                }
            }
            catch
            {
            }
        }

        public void Push(string msg)
        {

            try
            {
                var nativeQueue = _client.GetNativeQueue(_queueName);
                //var sendMessageResponse = nativeQueue.SendMessage("Hello world!", 10, 4);
                var sendMessageRequest = new SendMessageRequest(msg);

                var sendMessageResponse = nativeQueue.SendMessage(sendMessageRequest);
            }
            catch
            {
            }
        }
    }
}
